﻿using System;
using System.IO;
using System.Text;
using WikiDoc.Formatter;

namespace WikiDoc.Parser
{
    /// <summary>
    /// 
    /// </summary>
    public class CsvParser : IParser
    {

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get { return "csv"; }
        }

        /// <summary>
        /// Processes the specified parser.
        /// </summary>
        /// <param name="argv">The argv.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="formatter">The formatter.</param>
        public void Process(string argv, TextReader reader, IFormatter formatter)
        {
            if (reader == null) throw new ArgumentNullException("reader");
            if (formatter == null) throw new ArgumentNullException("formatter");

            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }

            char[] splitter = { ',', '，' };

            if (!string.IsNullOrEmpty(argv))
            {
                argv = argv.Replace(@"\s", " \t");
                argv = argv.Replace(@"\t", "\t");
                argv = argv.Replace(@"\\", @"\");

                splitter = argv.ToCharArray();
            }

            formatter.BeginTag("table");

            string line;

            while ( (line = reader.ReadLine()) != null)
            {
                if (line.Trim().Length == 0) continue;

                string[] cols = line.Split(splitter);

                formatter.BeginTag("tr");
                foreach (string s in cols)
                {
                    formatter.BeginTag("td");
                    formatter.AppendContent(WikiTranslater.SimpleTranslate(s));
                    formatter.EndTag("td");
                }
                formatter.EndTag("tr");
            }
            formatter.EndTag("table");
        }

    }
}